package com.haojiang.mh.remote.ui.dialog

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.zxing.Result
import com.haojiang.mh.R
import com.haojiang.mh.remote.adapter.ClientBedDialogFragAdapter
import com.haojiang.mh.remote.base.BaseDialogFrag
import com.haojiang.mh.remote.bean.BleRssiDevice
import com.haojiang.mh.remote.enums.EConnect
import com.haojiang.mh.remote.enums.EStep
import com.haojiang.mh.remote.event.ConnectEvent
import com.haojiang.mh.remote.ui.activity.QrcodeActivity
import com.haojiang.mh.remote.utils.BleUtil
import com.haojiang.mh.remote.utils.BleUtil.Companion.lastConnect
import com.haojiang.mh.remote.utils.BleUtil.Companion.saveGroupInterfaceNo
import com.haojiang.mh.remote.utils.Constant.QRRM
import com.haojiang.mh.remote.utils.SurfaceKey
import com.tamsiree.rxfeature.scaner.OnRxScanerListener
import kotlinx.android.synthetic.main.frag_dialog_select_bed.*
import org.greenrobot.eventbus.EventBus
import java.util.*
import kotlin.collections.ArrayList

class SelecBedDialogFrag : BaseDialogFrag() {

    /**
     * 伴生函数
     */
    companion object {
        private var GROUP_TYPE = "group_type"
        private var GROUP_ID = "group_id"
        val instance by lazy {
            SelecBedDialogFrag()
        }

        fun show(fragmentActivity: FragmentActivity, groupType: Int, groupId: Long) {
            val fm = fragmentActivity.supportFragmentManager
            fm.executePendingTransactions()
            fm.beginTransaction().remove(instance)
            instance.arguments = Bundle(bundleOf(GROUP_TYPE to groupType, GROUP_ID to groupId))
            instance.show(fm, SelecBedDialogFrag::class.java.simpleName)
        }
    }

    private var groupType = EConnect.CONNECT_GROUP_SINGLE.data
    private var groupId = 0L

    val clientBedDialogFragAdapter = ClientBedDialogFragAdapter()

//    private val onClickListener = object : View.OnClickListener {
//        override fun onClick(v: View?) {
//            if (v != null) {
//                when (v.id) {
//                    R.id.tvConfirm -> {
//                        val interfaceNo = etInterface.text.toString().trim()
//                        if (interfaceNo.length != 4) {
//                            showToast(getString(R.string.m_enter_4bit_interface_no))
//                        } else {
//                            searchInterface(interfaceNo)
//                        }
//                    }
//                    R.id.ivClose -> {
//                        dismiss()
//                    }
//                }
//            }
//        }
//    }


//    private val mIPermissionCallback = IPermissionCallback {
//        QrcodeActivity.setScanerListener(onRxScanerListener)
//        scanQrcode()
//    }

    override fun onSubCreate(savedInstanceState: Bundle?) {
        setStyle(STYLE_NO_TITLE, R.style.fragment_dialog_fullscreen)
        groupType = arguments!!.getInt(GROUP_TYPE)
        groupId = arguments!!.getLong(GROUP_ID)
    }

    override fun onSubCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.frag_dialog_select_bed, container, false)
    }

    override fun onSubViewCreated(view: View, savedInstanceState: Bundle?) {
        dialog!!.setCancelable(true) //是否可以点击取消
        dialog!!.setCanceledOnTouchOutside(true) //dialog外面是否可以点击

//        val params = dialog!!.window!!.attributes
//        val context = context
//        context?.let {
//            //            params.width = (Util.getScreenWidth(context) * 0.7f).toInt()
//            params.width = LinearLayout.LayoutParams.MATCH_PARENT
//            params.height = LinearLayout.LayoutParams.MATCH_PARENT
//            params.gravity = Gravity.CENTER
//            //高度自己定义
//            dialog!!.window!!.setLayout(params.width, params.height)
//        }
    }


    override fun onSubActivityCreated(savedInstanceState: Bundle?) {

//        ivQrcode.setOnClickListener(View.OnClickListener {
//            context?.let {
//                if (!Util.checkBleStatus(it)) {
//                    return@OnClickListener
//                }
//            }
//            PermissionManager.getInstance().setIPermissionCallback(mIPermissionCallback)
//            PermissionManager.getInstance().requestPermission(
//                context,
//                arrayOf(
//                    Manifest.permission.ACCESS_FINE_LOCATION,
//                    Manifest.permission.CAMERA,
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE
//                )
//            )
//        })

        rvClientBed.layoutManager = LinearLayoutManager(context)
        rvClientBed.adapter = clientBedDialogFragAdapter
        ivBack.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                this@SelecBedDialogFrag.dismiss()
            }
        })
        btnNext.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                val interfaceNo = clientBedDialogFragAdapter.getSelectInterfaceNo()
                if (!TextUtils.isEmpty(interfaceNo)) {
                    saveGroupInterfaceNo(groupId, interfaceNo)
                    dismiss()
                    EventBus.getDefault().post(
                        ConnectEvent(
                            EStep.STEP_SELECT_INTERFACE.data,
                            lastConnect.connectType,
                            groupId
                        )
                    )
                }
            }
        })
//        ivClose.setOnClickListener(onClickListener)
//
//        etInterface.setTransformationMethod(object : ReplacementTransformationMethod() {
//            override fun getOriginal(): CharArray {
//                return charArrayOf(
//                    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
//                )
//            }
//
//            override fun getReplacement(): CharArray {
//                return charArrayOf(
//                    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
//                )
//            }
//        })

//        etInterface.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
//            //当actionId == XX_SEND 或者 XX_DONE时都触发
//            //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
//            //注意，这是一定要判断event != null。因为在某些输入法上会返回null。
//            //                if (actionId == EditorInfo.IME_ACTION_SEND
//            //                        || actionId == EditorInfo.IME_ACTION_DONE
//            //                        || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
//            if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
//                KeyboardUtil.hideKeyboard(etInterface)
//                //处理事件
//            }
//            false
//        })

//        initInterfaceNo()    //设置界面编号
    }

//    private fun initInterfaceNo() {
//        val interfaceNo = readInterfaceNo()
//        if (TextUtils.isEmpty(interfaceNo)) {
//            etInterface.setText(null)
//        } else {
//            etInterface.setText(interfaceNo)
//        }
//    }


    private val onRxScanerListener = object : OnRxScanerListener {
        override fun onSuccess(type: String?, result: Result?) {
            result?.let {
                val interfaceNo = result.text.trim()
                if (interfaceNo.length < 4) {
                    showToast(getString(R.string.m_interface_not_exist))
                } else {
                    searchSurface(interfaceNo)
                }
            }
        }

        override fun onFail(type: String?, message: String?) {
        }
    }

    private fun searchSurface(surfaceNo: String) {
//        val funList = SurfaceKey.keyMap.get(interfaceNo.substring(0, 4).toUpperCase(Locale.ROOT))
//        if (funList == null || surfaceNo.equals(QRRM, ignoreCase = true)) {
        if (BleUtil.isSurfaceExist(surfaceNo) || surfaceNo.equals(QRRM, ignoreCase = true)) {
            showToast(getString(R.string.m_interface_not_exist))
            return
        } else {
            saveGroupInterfaceNo(groupId, surfaceNo)
            dismiss()

//            devConnects(context!!, lastBleDeviceList)   //连接蓝牙设备
//            EventBus.getDefault().post(FunctionEvent(funList))
            val bleDeviceList = ArrayList<BleRssiDevice>()
            lastConnect.bleDeviceList.forEach {
                bleDeviceList.add(it)
            }
            EventBus.getDefault().post(
                ConnectEvent(
                    EStep.STEP_SELECT_INTERFACE.data,
                    lastConnect.connectType,
                    groupId,
                    bleDeviceList
                )
            )

        }
    }

    override fun initDestroy() {
    }


    private fun scanQrcode() {
        startActivity(Intent(activity, QrcodeActivity::class.java))
    }
}